/**
 * Created by guohui on 17/2/16.
 * http配置
 */
import axios from 'axios'
import store from '../../../store/index'
import router from '../../../router'
// import allType from '../store/types'

// import goodStorage from 'good-storage'

// import {status} from 'api/config'
// import qs from 'qs'
// import { mapMutations } from 'vuex'

// ...mapMutations({
//     setSinger: 'SET_SINGER'
//   })
// axios 配置
axios.defaults.timeout = 1000000
axios.defaults.baseURL = ''
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
// console.log(qs.stringify)
// axios.defaults.transformRequest = [function (data) {
//   // var params = new URLSearchParams()
//   // for (var p in data) {
//   //   params.append(p, data[p])
//   // }
//   // data.forEach(function (item, index) {
//   //   params.append(item)
//   // })
//   // return params
//   // params.append('param2', 'value2')
//   // console.log(qs.stringify(data, {arrayFormat: 'indices'}))
//   return JSON.stringify(data)
// }]
// http request 拦截器
axios.interceptors.request.use(
  config => {
    config.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
    if (store.state.modules.user.token) {
      config.headers['x-access-token'] = `${store.state.modules.user.token}`
    }
    return config
  },
  err => {
    return Promise.reject(err)
  }
)
// http response 拦截器
axios.interceptors.response.use(
  response => {
    console.info(response)
    if (response.data.code === 401) {
      store.commit('REMOVE_USER', '')
      router.replace(
        {
          path: 'login',
          query: {redirect: router.currentRoute.fullPath}
        }
      )
      // store.commit(allType.user.SET_USER, '')
    }
    if (response.data.token) {
      console.info(1)
      // store.commit('SET_TOKEN', response.data.token)
      // store.commit(allType.user.SET_TONKEN, response.headers('token'))
      // store.commit(allType.user.SET_REFRESHTOKEN, response.headers('refreshToken'))
    }
    // console.log(response)
    return response
  },
  error => {
    if (error.response) {
      if (error.response.status === 401) {
        // 401 清除token信息并跳转到登录页面
        router.replace(
          {
            path: 'login',
            query: {redirect: router.currentRoute.fullPath}
          }
        )
        // store.commit(allType.user.SET_USER, {})
        // goodStorage.remove('user')
      }
    }
    return Promise.reject(error)
  }
)

export default axios
